package com.yuanfeng.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.business.dto.GdbMerchantTransportAreaDTO;
import com.yuanfeng.business.dto.ManagetransportAreaDeleteDTO;
import com.yuanfeng.business.dto.UserTokenBeanDTO;
import com.yuanfeng.business.dto.WapTransportAreaQueryDTO;
import com.yuanfeng.business.entity.ShopTransportAreaEntity;
import com.yuanfeng.business.feign.BaseServiceClient;
import com.yuanfeng.business.feign.GoodsServiceClient;
import com.yuanfeng.business.mapper.ShopTransportAreaMapper;
import com.yuanfeng.business.service.ShopTransportAreaService;
import com.yuanfeng.business.vo.TransportAreaVO;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.vo.goods.GdsBaseDetailResultVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName ShopTransportAreaServiceImpl
 * @Description 售卖区域表
 * @Author cyp
 * @Date 2023-05-26 10:12:34
 * @Version 1.0
 **/
@Service
public class ShopTransportAreaServiceImpl extends ServiceImpl<ShopTransportAreaMapper, ShopTransportAreaEntity>
        implements ShopTransportAreaService {
    @Autowired
    private GoodsServiceClient goodsServiceClient;
    @Autowired
    private ShopTransportAreaMapper shopTransportAreaMapper;
    @Autowired
    private BaseServiceClient baseServiceClient;
    @Override
    public ResponseResult query(WapTransportAreaQueryDTO param) {
        List<List<Integer>> results = new ArrayList<List<Integer>>();
        // transportAreaMapper
        // 查询所有的区域id
        List<List<Integer>> shopCommonIds = param.getShopGoodsIds();
        List<Integer> goodsIds = new ArrayList<Integer>();
        for (List<Integer> commonIds : shopCommonIds) {

            if (commonIds.size() == 1) {
                int stock = 0;
                // 查询商品状态 及 库存
                List<GdsBaseDetailResultVO> goodsBases = goodsServiceClient.queryGoodsStartStock(commonIds.get(0));
                for(GdsBaseDetailResultVO tmp: goodsBases){
                    goodsIds.add(tmp.getGoodsId());
                    if(tmp.getGoodsIsShelves() == 1 && tmp.getCommonState() == 1 && tmp.getCommonVerify() == 1){
                        stock = stock + tmp.getGoodsStock();
                    }
                }
                List<Integer> result = new ArrayList<Integer>();

                if (stock == 0) {
                    result.add(0);
                    results.add(result);
                    return ResponseResult.success(results);
                }
            }
            //查询当前商品商品的 售卖区域规则
            List<Integer> transportAreaIds = goodsServiceClient.selectTransportAreaId(goodsIds);
            if (!CollectionUtils.isEmpty(transportAreaIds)) {
                List<Integer> result = new ArrayList<Integer>();

                for (Integer transportAreaId : transportAreaIds) {
                    //查询当前售卖区域模板下 的城市Id
                    String shopAreaIds = this.baseMapper.selectByTransportAreaIds(transportAreaId);

                    // 全国有货
                    if (null != shopAreaIds && !shopAreaIds.equals("") && shopAreaIds.equals("0")) {
                        result.add(1);// 表示有货
                        results.add(result);
                        return ResponseResult.success(results);
                    } else {
                        // 省市区id是否的标记
                        boolean flag = false;
                        if (null != shopAreaIds && !shopAreaIds.equals("")) {
                            // 判断传入区域是否有货
                            List<String> areaIdsList = Arrays.asList(shopAreaIds.split(","));
                            // 获取需要判断的id
                            List<Integer> needAreaIds = param.getAreaIds();

                            if (needAreaIds.size() >= 2) {
                                if (areaIdsList.contains(needAreaIds.get(1).toString())) {
                                    result.add(1);// 表示有货
                                    flag = true;
                                    // break;
                                }
                            }
                        }

                        if (!flag) {
                            result.add(0);// 表示无货
                        }
                    }
                }
                results.add(result);
            } else {
                List<Integer> result = new ArrayList<Integer>();
                for (int i = 0; i < goodsIds.size(); i++) {
                    result.add(0);
                }
                results.add(result);

            }
        }
        if (CollectionUtils.isEmpty(results)) {
            return ResponseResult.fail(0, "无数据返回");
        }
        return ResponseResult.success(results);
    }

    @Override
    public ResponseResult queryTwo(WapTransportAreaQueryDTO param) {
        List<Integer> results = new ArrayList<>();
        // transportAreaMapper
        // 查询所有的区域id
        List<List<Integer>> shopCommonIds = param.getShopGoodsIds();
        List<Integer> commonIds = shopCommonIds.get(0);
        for (Integer commonId : commonIds) {
            Integer transportAreaId  = this.baseMapper.selectTransportAreaId(commonId);
            if (null != transportAreaId) {
                List<Integer> result = new ArrayList<Integer>();
                String shopAreaIds = this.baseMapper.selectByTransportAreaIds(transportAreaId);
                // 全国有货
                if (null != shopAreaIds && !shopAreaIds.equals("") && shopAreaIds.equals("0")) {
                    results.add(1);// 表示有货
                } else {
                    // 省市区id是否的标记
                    boolean flag = false;
                    if (null != shopAreaIds && !shopAreaIds.equals("")) {
                        // 判断传入区域是否有货
                        List<String> areaIdsList = Arrays.asList(shopAreaIds.split(","));
                        // 获取需要判断的id
                        List<Integer> needAreaIds = param.getAreaIds();
                        if (needAreaIds.size() >= 2) {
                            if (areaIdsList.contains(needAreaIds.get(1).toString())) {
                                results.add(1);// 表示有货
                                flag = true;
                                // break;
                            }
                        }
                    }
                    if (!flag) {
                        results.add(0);// 表示无货
                    }
                }
            }
        }
        if (CollectionUtils.isEmpty(results)) {
            return ResponseResult.fail(0, "无数据返回");
        }
        return ResponseResult.success(results);
    }

    @Override
    @Transactional
    public ResponseResult delete(ManagetransportAreaDeleteDTO param) {

        // 权限判断
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(param.getToken());

        if (userInfoVO != null) {
            // 删除售卖区域
            this.baseMapper.deleteByPrimaryKey(param.getTransportAreaId());

        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(), BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success();
    }

    @Override
    @Transactional
    public ResponseResult add(GdbMerchantTransportAreaDTO param) {

        // 权限判断
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(param.getToken());

        if (userInfoVO != null) {
            param.setShopId(Integer.valueOf(userInfoVO.getShopId()));


            // 新增或更新售卖区域
            if (null == param.getId()) {
                shopTransportAreaMapper.insertSelective(param);
            } else {
                shopTransportAreaMapper.updateByPrimaryKeySelective(param);
            }
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(), BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success();
    }


    @Override
    public ResponseResult queryDetail(ManagetransportAreaDeleteDTO param) {
        TransportAreaVO area = new TransportAreaVO();
        // 权限判断
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(param.getToken());

        if (userInfoVO != null) {
            // 查询售卖区域
            area = shopTransportAreaMapper.selectByTransportAreaId(param.getTransportAreaId());
            if (area.getAreaIds().equals("0")) {
                area.setAreaNames("全国");
            } else {
                // 根据district_id查询地区名称
                List<Integer> districtIds = JsonUtils.StringToList2(area.getAreaIds());
                List<String> districtNames = baseServiceClient.queryDistrictName(districtIds);
                area.setAreaNames(JSON.toJSONString(districtNames));
            }

        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(), BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success(area);
    }

    @Override
    public ResponseResult selectAreaById(Integer transportAreaId) {
        ShopTransportAreaEntity entity=this.baseMapper.selectById(transportAreaId);
        return ResponseResult.success(entity);
    }

    @Override
    public ResponseResult queryArea(UserTokenBeanDTO param) {
        UserInfoVO userinfo = ParseTokenUtils.getUserInfoByTokenNoIsExist(param.getToken());// 获取user信息
        if (userinfo == null){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        // 查询售卖区域
        List<TransportAreaVO> areas = getTransportArea(Integer.valueOf(userinfo.getShopId()));
        return ResponseResult.success(areas);
    }

    /**
     * 获取售卖区域
     *
     * @param shopId
     * @return
     */
    private List<TransportAreaVO> getTransportArea(Integer shopId) {
        List<TransportAreaVO> areas = this.baseMapper.selectByShopId(shopId);
        for (TransportAreaVO area : areas) {
            if (null == area.getAreaIds() || area.getAreaIds().equals("")) {
                area.setAreaIds("0");
            }
            if (area.getAreaIds().equals("0")) {
                area.setAreaNames("全国");
            } else {
                // 根据district_id查询地区名称
                List<Integer> districtIds = JsonUtils.StringToList2(area.getAreaIds());
                List<String> districtNames = this.baseMapper.selectByIdList(districtIds);
                area.setAreaNames(JSON.toJSONString(districtNames));
            }
        }
        return areas;
    }
}
